//
//  SystemMessageVC.m
//  EDF
//
//  Created by p on 2019/7/11.
//  Copyright © 2019年 p. All rights reserved.
//

#import "SystemMessageVC.h"
#import "SystemTableHeadView.h"
#import "MessageCell.h"
#import "MessageModel.h"
#define headViewHeight RealValue_H(130)
@interface SystemMessageVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) NSMutableArray * dataArray;//
@property (nonatomic,strong) SystemTableHeadView * tableviewHeadView;
@property (nonatomic,strong) NoNetworkView * workView;
@property (nonatomic,assign) BOOL isNewMessage;
@property (nonatomic,assign) NSInteger count;
@end

@implementation SystemMessageVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = WHITECOLOR;
    [self.view addSubview:self.tableView];
   
    [self getDatalist:@"1"];
}


#pragma mark----Action数据
/*获取系统消息*/
- (void)getDatalist:(NSString *)status
{
    if ([status isEqualToString:@"1"]) {
        _isNewMessage = YES;
    }else
    {
         _isNewMessage = NO;
    }
    [self showLoadingAnimation];
    WeakSelf
    NSString  * AllGame = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"loadSystemMsg"];
    [[SmileHttpTool sharedInstance] GET :AllGame parameters:@{@"status":status} origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
        NSDictionary * dict = [WJUnit dictionaryWithJsonString:responseObject];
       
        if ([[dict jsonString:@"statusCode"] isEqualToString:@"SUCCESS"]) {
            NSDictionary * dic = [self objectFromJSONString:responseObject];
            weakSelf.dataArray  = [MessageModel mj_objectArrayWithKeyValuesArray:dic[@"data"][@"date"]];
            weakSelf.count =  weakSelf.dataArray.count;
           
            if (weakSelf.isNewMessage) {
                 [weakSelf getRedcount:weakSelf.count];
            }
           
            for (MessageModel * model in weakSelf.dataArray)
            {
                model.isOpen = NO;
                model.isRead = @"1";
          
                NSString *str = [model.content stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                NSData *data = [str dataUsingEncoding:NSUnicodeStringEncoding];
                NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
                NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
                [attr addAttribute:NSFontAttributeName value:AutoFont(14) range:NSMakeRange(0, attr.length)];
               CGSize attSize = [attr boundingRectWithSize:CGSizeMake(UIScreenWidth -30, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;
                if (!kStringIsEmpty(model.content_id)) {
                    [self requestModelImageWith:model isopen:NO];
                      model.cellHeight =attSize.height +64 +50+(kScreenWidth-30)*0.4;
                }else{
                      model.cellHeight =attSize.height +64 +50;
                }
              
                model.mucontent = attr;
            }
            [self placeholderViewWithFrame:CGRectMake(0, 100, UIScreenWidth, weakSelf.tableView.height -100) NoNetwork:NO];
            [weakSelf.tableView reloadData];
            
        }else{
            [JMNotifyView showNotify:[dict jsonString:@"message"]  isSuccessful:NO];
        }
         [self stopLoadingAnimation];
        
    } failure:^(id responseObject, NSError *error) {
        [self stopLoadingAnimation];
        [WJUnit showMessage:@"请求错误"];
    }];
}
-(void)requestModelImageWith:(MessageModel *)messModel isopen:(BOOL)isopen{
    if (isopen==YES) {
        [self showLoadingAnimation];
    }
    NSString  * AllGame = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"loadMsgImageContent"];
    [[SmileHttpTool sharedInstance] GET :AllGame parameters:@{@"content_id":messModel.content_id} origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
        NSDictionary * dict = [WJUnit dictionaryWithJsonString:responseObject];
        if ([[dict jsonString:@"statusCode"] isEqualToString:@"SUCCESS"]) {
            NSDictionary * dataDicc = [dict jsonDict:@"data"];
            messModel.imageData = [dataDicc jsonString:@"img"];
            YYLog(@"loadMsgImageContent-----%@",dict);
            if (!kStringIsEmpty( [dataDicc jsonString:@"text"])) {
                messModel.content =[dataDicc jsonString:@"text"];
                NSString *str = [messModel.content stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                NSData *data = [str dataUsingEncoding:NSUnicodeStringEncoding];
                NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
                NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
                [attr addAttribute:NSFontAttributeName value:AutoFont(14) range:NSMakeRange(0, attr.length)];
                CGSize attSize = [attr boundingRectWithSize:CGSizeMake(UIScreenWidth -30, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;
                  messModel.cellHeight =attSize.height +64 +50+(kScreenWidth-30)*0.4;
                    messModel.mucontent = attr;
                
            }
            [self.tableView reloadData];
        }else{
          //  [JMNotifyView showNotify:[dict jsonString:@"message"]  isSuccessful:NO];
        }
        if (isopen==YES) {
            [self stopLoadingAnimation];
        }
    } failure:^(id responseObject, NSError *error) {
      //  [self stopLoadingAnimation];
      //  [WJUnit showMessage:@"请求错误"];
        if (isopen==YES) {
            [self stopLoadingAnimation];
        }
    }];
    
    
    
}
- (void)placeholderViewWithFrame:(CGRect)frame NoNetwork:(BOOL)NoNetwork
{
    if (self.dataArray.count == 0)
    {
        [_workView removeFromSuperview];
        _workView = [[NoNetworkView alloc] initWithFrame:frame NoNetwork:NoNetwork];
        
        [_tableView addSubview:_workView];
    }else
    {
        [_workView dissmiss];
    }
}
#pragma  mark -----懒加载
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, UIScreenHeight -kStatusBarAndNavigationBarHeight -  RealValue_H(100))style:UITableViewStyleGrouped];
        _tableView.tableFooterView = [UIView new];
         _tableView.separatorColor = RGBA(210, 210, 210, 1);
        _tableView.delegate = self;
        _tableView.dataSource=self;
        _tableView.backgroundColor = WHITECOLOR;
        _tableView.showsVerticalScrollIndicator = NO;
        
        [_tableView registerNib:[UINib nibWithNibName:@"MessageCell" bundle:nil]  forCellReuseIdentifier:@"MessageCell"];
        _tableView.tableHeaderView =self.tableviewHeadView;
    }
    return _tableView;
}
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
- (SystemTableHeadView*)tableviewHeadView{
    WeakSelf
    if (!_tableviewHeadView) {
        _tableviewHeadView =[[ SystemTableHeadView alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, headViewHeight)];
        _tableviewHeadView.indexBlock = ^(NSInteger index) {
            if (index ==0)
            {
                [weakSelf getDatalist:@"1"];
            }else
            {
                [weakSelf getDatalist:@"0"];
            }
           
        };

    }
    return _tableviewHeadView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return _dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MessageModel * model = _dataArray[indexPath.row];
    if (model.isOpen)
    {
         return model.cellHeight +80;
    }else
    {
        return 64;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MessageCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"MessageCell" forIndexPath:indexPath];
    MessageModel * model = _dataArray[indexPath.row];
    cell.model = model;
    if (model.isOpen) {
        cell.textview.hidden = NO;
        cell.contentImage.hidden = NO;
        cell.openBtn.selected = YES;
    }else
    {
        cell.textview.hidden = YES;
        cell.contentImage.hidden = YES;
        cell.openBtn.selected = NO;
    }
    [cell.zanButton add_BtnClickHandler:^(NSInteger tag) {
        if ([model.zan isEqualToString:@"是"] && ![model.already_praise isEqualToString:@"是"]) { //点赞
            
            [self showLoadingAnimation];
            WeakSelf
            NSString  * AllGame = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"markPraise"];
            [[SmileHttpTool sharedInstance] GET :AllGame parameters:@{@"msg_id":model.id} origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
                NSDictionary * dict = [WJUnit dictionaryWithJsonString:responseObject];
                [self stopLoadingAnimation];
                if ([[dict jsonString:@"statusCode"] isEqualToString:@"SUCCESS"]) {
                   
                    model.already_praise = @"是";
                    NSIndexPath *index=[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
                    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:index,nil] withRowAnimation:UITableViewRowAnimationNone];
                    
                }else{
                    [JMNotifyView showNotify:[dict jsonString:@"message"]  isSuccessful:NO];
                }
                
            } failure:^(id responseObject, NSError *error) {
                [self stopLoadingAnimation];
                [WJUnit showMessage:@"请求错误"];
            }];
        }
        
    }];
    [cell.readButton add_BtnClickHandler:^(NSInteger tag) { //已阅读
        if (![model.already_read isEqualToString:@"是"]) {
            
            [self showLoadingAnimation];
            WeakSelf
            NSString  * AllGame = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"markRead"];
            [[SmileHttpTool sharedInstance] GET :AllGame parameters:@{@"msg_id":model.id} origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
                NSDictionary * dict = [WJUnit dictionaryWithJsonString:responseObject];
                [self stopLoadingAnimation];
                if ([[dict jsonString:@"statusCode"] isEqualToString:@"SUCCESS"]) {
                  
                    model.already_read = @"是";
                    NSIndexPath *index=[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
                    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:index,nil] withRowAnimation:UITableViewRowAnimationNone];
                    
                }else{
                    [JMNotifyView showNotify:[dict jsonString:@"message"]  isSuccessful:NO];
                }
                
            } failure:^(id responseObject, NSError *error) {
                [self stopLoadingAnimation];
                [WJUnit showMessage:@"请求错误"];
            }];
            
        }
    }];
    cell.messageIcon.image = [UIImage imageNamed:_isNewMessage?@"newMessage":@"oldMessage"];
    WeakSelf
    [cell.openBtn add_BtnClickHandler:^(NSInteger tag) {
         model.isOpen = !model.isOpen;
 
        for (MessageModel * mess in weakSelf.dataArray)
        {
            if (![mess.id isEqualToString:model.id]) {
                mess.isOpen = NO;
            }
        
        }
        [self.tableView reloadData];
    }];
    [cell.deleteButton add_BtnClickHandler:^(NSInteger tag) { //删除消息
        [self showLoadingAnimation];
        WeakSelf
        NSString  * AllGame = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"deleteSystemMsg"];
        [[SmileHttpTool sharedInstance] GET :AllGame parameters:@{@"msg_id":model.id} origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
            NSDictionary * dict = [WJUnit dictionaryWithJsonString:responseObject];
            [self stopLoadingAnimation];
            if ([[dict jsonString:@"statusCode"] isEqualToString:@"SUCCESS"]) {
                ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:2 andImageName:@"success" andTitleStr:@"删除成功" andlightStr:@""];
                [toast showLXAlertView];
                [weakSelf.dataArray removeObjectAtIndex:indexPath.row];
                // 刷新
                [weakSelf.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
                
            }else{
                [JMNotifyView showNotify:[dict jsonString:@"message"]  isSuccessful:NO];
            }
            
        } failure:^(id responseObject, NSError *error) {
            [self stopLoadingAnimation];
            [WJUnit showMessage:@"请求错误"];
        }];
    }];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MessageModel * model = _dataArray[indexPath.row];
    model.isOpen = !model.isOpen;
    if (!kStringIsEmpty(model.content_id) && kStringIsEmpty(model.imageData) && model.isOpen ==YES) {
        [self requestModelImageWith:model isopen:YES];
    }
    for (MessageModel * mess in _dataArray)
    {
        if (![mess.id isEqualToString:model.id]) {
            mess.isOpen = NO;
        }
        
    }
   
    if (self.isNewMessage) {
        if (model.isOpen) {
            if (model.isRead.integerValue ==1)
            {
                [self showLoadingAnimation];
                WeakSelf
                NSString  * AllGame = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"readMsg"];
                [[SmileHttpTool sharedInstance] GET :AllGame parameters:@{@"msg_id":model.id} origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
                    NSDictionary * dict = [WJUnit dictionaryWithJsonString:responseObject];
                    [self stopLoadingAnimation];
                    if ([[dict jsonString:@"statusCode"] isEqualToString:@"SUCCESS"]) {
                        model.isRead = @"2";
                        weakSelf.count =  weakSelf.count-1;
                        [weakSelf getRedcount:weakSelf.count];
                        weakSelf.tableviewHeadView.redlable.text = kFormat(@"%ld", (long)weakSelf.count);
                    }else{
                        [JMNotifyView showNotify:[dict jsonString:@"message"]  isSuccessful:NO];
                    }
                    
                } failure:^(id responseObject, NSError *error) {
                    [self stopLoadingAnimation];
                    [WJUnit showMessage:@"请求错误"];
                }];
            }
        }
    }
    
    [self.tableView reloadData];
}
- (void)getRedcount:(NSInteger)count
{
    if (count<=0) {
        self.tableviewHeadView.redlable.hidden = YES;
    }else
    {
        self.tableviewHeadView.redlable.hidden = NO;
    }
    self.tableviewHeadView.redlable.text = kFormat(@"%ld", (long)count);
}
@end
